/**
 * Notes: 聊天记录管理服务
 * Date: 2023-10-01 19:40:00 
 */

const BaseProjectAdminService = require('./base_project_admin_service.js');
const ChatModel = require('../../model/chat_model.js');
const timeUtil = require('../../../../framework/utils/time_util.js');
const util = require('../../../../framework/utils/util.js');

class AdminChatService extends BaseProjectAdminService {

    /**
     * 获取聊天记录列表
     * @param {object} adminId 管理员ID
     * @param {object} condition 查询条件
     * @param {object} options 选项
     * @param {object} options.search 搜索内容
     * @param {object} options.sortType 排序类型
     * @param {object} options.sortVal 排序值
     * @param {object} options.userId 用户ID
     * @param {object} options.page 页码
     * @param {object} options.size 页大小
     * @param {object} options.isTotal 是否返回总页数
     * @param {object} options.oldTotal 上次总页数
     */
    async getChatList({
        search = '',
        sortType = '',
        sortVal = '',
        userId = '',
        page = 1,
        size = 10,
        isTotal = true,
        oldTotal = 0
    }) {
        // 设置查询条件
        const where = {};

        // 搜索条件
        if (search) {
            where.or = [
                { CHAT_QUESTION: { $regex: search, $options: 'i' } },
                { CHAT_ANSWER: { $regex: search, $options: 'i' } },
                { CHAT_USER_NAME: { $regex: search, $options: 'i' } }
            ];
        }

        // 按用户筛选
        if (userId) {
            where.CHAT_USER_ID = userId;
        }

        // 设置排序方式
        let orderBy = {
            CHAT_ADD_TIME: 'desc'
        };

        // 自定义排序
        if (sortType && sortVal) {
            orderBy = {
                [sortType]: sortVal
            };
        }

        // 查询数据
        const result = await ChatModel.getList(where, orderBy, page, size, isTotal, oldTotal);

        return result;
    }

    /**
     * 获取聊天记录详情
     * @param {object} adminId 管理员ID
     * @param {string} id 聊天记录ID
     */
    async getChatDetail(adminId, id) {
        this._checkAdminId(adminId);

        if (!id) throw new Error('未指定聊天记录ID');

        const chat = await ChatModel.getOne(id);
        if (!chat) throw new Error('聊天记录不存在');

        return chat;
    }

    /**
     * 删除聊天记录
     * @param {object} adminId 管理员ID
     * @param {string} id 聊天记录ID
     */
    async delChat(adminId, id) {
        this._checkAdminId(adminId);

        if (!id) throw new Error('未指定聊天记录ID');

        const chat = await ChatModel.getOne(id);
        if (!chat) throw new Error('聊天记录不存在');

        // 软删除
        const data = {
            CHAT_STATUS: ChatModel.STATUS.DELETED,
            CHAT_EDIT_TIME: timeUtil.time(),
            CHAT_EDIT_IP: this._getIP()
        };

        await ChatModel.edit(id, data);

        return {
            id
        };
    }

    /**
     * 获取聊天统计数据
     * @param {object} adminId 管理员ID
     * @param {object} options 选项
     * @param {string} options.startDate 开始日期
     * @param {string} options.endDate 结束日期
     */
    async getChatStats(adminId, { startDate = '', endDate = '' }) {
        this._checkAdminId(adminId);

        // 默认统计最近30天
        if (!startDate) {
            const now = new Date();
            const thirtyDaysAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
            startDate = timeUtil.time('Y-M-D', thirtyDaysAgo.getTime() / 1000);
        }

        if (!endDate) {
            endDate = timeUtil.time('Y-M-D');
        }

        // 转换为时间戳
        const startTimestamp = timeUtil.time2Timestamp(startDate + ' 00:00:00');
        const endTimestamp = timeUtil.time2Timestamp(endDate + ' 23:59:59');

        // 查询总记录数
        const totalCount = await ChatModel.count({
            CHAT_ADD_TIME: {
                $gte: startTimestamp,
                $lte: endTimestamp
            }
        });

        // 查询用户数量
        const userCount = await ChatModel.distinctCount('CHAT_USER_ID', {
            CHAT_ADD_TIME: {
                $gte: startTimestamp,
                $lte: endTimestamp
            }
        });

        // 查询未回答问题数
        const pendingCount = await ChatModel.count({
            CHAT_ADD_TIME: {
                $gte: startTimestamp,
                $lte: endTimestamp
            },
            CHAT_STATUS: ChatModel.STATUS.PROCESSING
        });

        // 构建按日期统计数据
        const statsByDate = [];
        let currentDate = new Date(startTimestamp * 1000);
        const endDate2 = new Date(endTimestamp * 1000);

        while (currentDate <= endDate2) {
            const dateStr = timeUtil.time('Y-M-D', currentDate.getTime() / 1000);
            const nextDate = new Date(currentDate);
            nextDate.setDate(nextDate.getDate() + 1);

            const dayStartTimestamp = currentDate.getTime() / 1000;
            const dayEndTimestamp = nextDate.getTime() / 1000 - 1;

            // 查询当天记录数
            const dayCount = await ChatModel.count({
                CHAT_ADD_TIME: {
                    $gte: dayStartTimestamp,
                    $lte: dayEndTimestamp
                }
            });

            // 查询当天用户数
            const dayUserCount = await ChatModel.distinctCount('CHAT_USER_ID', {
                CHAT_ADD_TIME: {
                    $gte: dayStartTimestamp,
                    $lte: dayEndTimestamp
                }
            });

            statsByDate.push({
                date: dateStr,
                count: dayCount,
                userCount: dayUserCount
            });

            currentDate = nextDate;
        }

        return {
            total: totalCount,
            users: userCount,
            pending: pendingCount,
            statsByDate
        };
    }
}

module.exports = AdminChatService; 